# --! coding=utf-8 !--
# coding=utf-8
# Copyright (c) [2025] [2578713815@qq.com]
# [AHPU_EQM] is licensed under Mulan PSL v2.
"""
跟时间操作相关的功能库\n
author: <2578713815@qq.com>\n
"""
import datetime
from threading import Event
import time
from CONFIG import settings
from Utils import dbUtils

RED = settings.RED
GREEN = settings.GREEN
YELLOW = settings.YELLOW
BLUE = settings.BLUE
GRAY = settings.GRAY
RESET = settings.RESET


def update_controller(event: Event):
	"""
	电量数据更新事件管控线程函数
	:param event: 信息更新事件
	:return:
	"""
	while True:
		now = datetime.datetime.now()
		# 检查当前时间是否在目标时间范围内
		if (check_current_time(settings.TARGET_HOUR_1, settings.TARGET_MINUTE, settings.TARGET_SECONDS, 60*30) or
				check_current_time(settings.TARGET_HOUR_2, settings.TARGET_MINUTE, settings.TARGET_SECONDS, 60*30)):
			print(f">>> Time {now.time()} | update data...")
			event.set()
			# 唤醒事件后等待足够的时间，确保不会在指定时间附近重复唤醒事件
			# 每12个小时更新一次本地数据库，直接等待6个小时
			time.sleep(60*60*6)
		else:
			time.sleep(60*30)


def servo_start_controller(event: Event) -> None:
	"""
	用户服务线程管控线程函数
	:param event: 用户服务启动事件
	:return:
	"""
	original_timestamp = int(time.time())
	while True:
		current_timestamp = int(time.time())
		# if (current_timestamp-original_timestamp) % (60*30) == 0 and (current_timestamp-original_timestamp) >= 60*30:
		if (current_timestamp - original_timestamp) % (60 * 30) == 0:
			event.set()
			# 启动后等待足够时间，避免重复唤醒
			time.sleep(60*15)
		else:
			time.sleep(1)
			continue


def clean_user_status_controller() -> None:
	"""
	用户信息状态管控函数，用于每日0点将statu属性归零
	:return:
	"""
	while True:
		if check_current_time(0, 0, 10):
			# 在每天凌晨将用户的消息发送状态归零
			dbUtils.clean_user_info_statu(settings.USERS_DATA_PATH)
			time.sleep(60)
		else:
			time.sleep(5)
			continue


def check_current_time(_target_hour_: int, _target_minute_: int, _target_second_,
					   _tolerance_second_: int = settings.TOLERANCE_SECOND) -> bool:
	"""
	基于时间戳，检查时间是否处于范围内
	:param _target_hour_: 目标小时列表
	:param _target_minute_: 目标分钟
	:param _target_second_: 目标秒
	:param _tolerance_second_: 时间范围（秒）
	:return:
	"""
	now = datetime.datetime.now()  # 当前时间对象
	current_timestamp = int(now.timestamp())  # 当前时间戳
	target_timestamp = get_daly_target_timestamp(_target_hour_, _target_minute_, _target_second_)
	if abs(current_timestamp - target_timestamp) < _tolerance_second_:
		return True
	else:
		return False


def get_daly_target_timestamp(_target_hour_: int, _target_minute_: int, _target_second_: int) -> int:
	"""
	获取每日指定时间的时间戳
	:param _target_hour_: 指定小时
	:param _target_minute_: 指定分钟
	:param _target_second_: 指定秒
	:return: 返回整数时间戳
	"""
	now_date = datetime.datetime.now().strftime("%Y-%m-%d")
	date_string = f"{now_date} {_target_hour_}:{_target_minute_}:{_target_second_}"
	time_format = "%Y-%m-%d %H:%M:%S"
	timestamp = datetime.datetime.strptime(date_string, time_format).timestamp()
	return int(timestamp)
